$(function () {
    obj.init();
});
var obj = new function () {
    'use strict';
    return {
        form:null,
        modelTr:null,
        init:function () {
            this.form = new xhForm($('#xh_form')).parse();
            this.modelTr = $('.modelTr').eq(0).clone();
            this.id = xhTool.getQuery('id');
            this.listener();
            if (formData) {
                this.funObj().initEditForm(formData);
            }
        },
        listener:function () {
            var $this = this;
            //新增按钮
            $('#addBtn').click(function () {
                $this.funObj().addProd();
            });
            //提交
            $('#bt_modal_confirm', parent.document).unbind('click').bind('click',function () {
                $this.funObj().submitFormAction();
            });
        },
        funObj:function () {
            var $this = this;
            return {
                initEditForm:function (formData) {
                    $this.form.fill(formData);
                    if(formData.mAccessory.length > 0) {
                        $.each(formData.mAccessory, function (i,item) {
                            $this.funObj().addProd();
                            var dom = $('.modelTr').eq(i);
                            dom.find('.prodName').val(item['name']);
                            dom.find('.num').val(item['num']);
                        });
                        $('.modelTr:last').remove();
                    }
                },
                addProd:function () {
                    var dom = $($this.modelTr.clone());
                    $('#addBtn').parent().parent().before(dom);
                },
                getCusProdData:function () {
                    var $arr = [];
                    $('.modelTr').each(function () {
                        var obj = {};
                        var dom = $(this);
                        obj.name = dom.find('.prodName').val();
                        obj.num    = dom.find('.num').val();
                        if (obj.num > 0 && obj.name) {
                            $arr.push(obj);
                        }
                    });
                    return $arr;
                },
                submitFormAction:function () {
                    var $params = {};
                    $params.mContent = $this.funObj().getCusProdData();
                    $this.form.submit('ims/produce/saveAccessory', $params, function (res) {
                        window.top.xhTop.showSuccess(res.msg);
                        window.top.xhTop.getActiveFrame().obj.prodDataGrade.reload();
                        window.top.xhTop.closeModal();
                    })
                }

            }
        }
    }
};